package com.bsb.base.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bsb.base.common.config.Global;

public class PicUtil extends Exceptions {
	private final static Logger log = Logger.getLogger(PicUtil.class);

	public static void getPhoto(String url, String path, HttpServletResponse response) {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		try {
			File file = new File(path + "/" + url);
			log.warn("获取图片真实路径为：" + path + "/" + url);
			InputStream inStream = null;
			inStream = new FileInputStream(file);
			byte data[] = readInputStream(inStream);
			if (url.contains(".")) {
				response.setContentType("image/" + url.substring(url.lastIndexOf(".") + 1)); // 设置返回的文件类型
			} else {
				response.setContentType("image/png"); // 设置返回的文件类型
			}
			OutputStream os = response.getOutputStream();
			os.write(data);
			os.flush();
			os.close();
		} catch (FileNotFoundException e) {
			log.error(getErrorMsg(e) + "文件名：" + url);
		} catch (IOException e) {
			log.error(getErrorMsg(e) + "获取图片" + url);
		}

	}

	public static byte[] readInputStream(InputStream inStream) {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[2048];
		int len = 0;
		try {
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return outStream.toByteArray();
	}

	public static String getPicUploadPath() {
		String path = "";
		String osName = System.getProperties().getProperty("os.name").toLowerCase();
		if (osName.contains("windows")) {
			path = Global.getConfig("windows.pic");
		} else if (osName.contains("linux")) {
			path = Global.getConfig("linux.pic");
		}
		log.warn("当前操作系统为：" + osName + ",当前文件路径：" + path);
		return path;
	}
	
	public static String getVoiceUploadPath() {
		String path = "";
		String osName = System.getProperties().getProperty("os.name").toLowerCase();
		if (osName.contains("windows")) {
			path = Global.getConfig("windows.voice");
		} else if (osName.contains("linux")) {
			path = Global.getConfig("linux.voice");
		}
		log.warn("当前操作系统为：" + osName + ",当前文件路径：" + path);
		return path;
	}

	public static void main(String[] args) {
		//
	}
}
